package com.demo.rabbitmq.amqp.pub;

import com.demo.rabbitmq.amqp.entity.Order;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;

/**
 * @author sc
 * Created on  2018/9/22
 */
@Component
public class RabbitSender {
    @Autowired
    private RabbitTemplate template;


    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){

        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            if(ack){
                System.out.println("corr "+correlationData);
            }else{
                System.out.println(cause);
            }
        }
    };

    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
            System.out.println(message);
            System.out.println(replyCode);
            System.out.println(replyText);
            System.out.println(exchange);
            System.out.println(routingKey);
        }
    };

    public void send(Object message, Map<String,Object> properties){
        MessageHeaders headers = new MessageHeaders(properties);
        Message msg = MessageBuilder.createMessage(message, headers);
        template.setConfirmCallback(confirmCallback);
        template.setReturnCallback(returnCallback);
        CorrelationData cd = new CorrelationData("only id");
        template.convertAndSend("test_sb","sb.ex",msg,cd) ;
    }


    public void sendOrder(Order message, Map<String,Object> properties){
        template.setConfirmCallback(confirmCallback);
        template.setReturnCallback(returnCallback);
        CorrelationData cd = new CorrelationData("only id");
        template.convertAndSend("order_ex","order.1",message,cd) ;
    }


}
